package drazing;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.text.NumberFormat;

/**
 * Clase auxiliar que implementa el cronometro de carrera
 * @author xcubo
 */
public class Cronometro implements Runnable
{
    private Tiempo time;
    private Thread crono;
    private boolean running;

    public Cronometro()
    {
        time = new Tiempo(0,0,0,0);
        running = true;

        crono = new Thread(this);
    }

    /**
     * Dibuja el cronómetro
     * @param g Graphics
     * @param x Coordenada x
     * @param y Coordenada y
     */
    public void print(Graphics g, float x, float y)
    {
        Graphics2D g2 = (Graphics2D)g;

        NumberFormat duo = NumberFormat.getInstance();
        duo.setMinimumIntegerDigits(2);

        String t = time.toString();


        FontRenderContext frc = g2.getFontRenderContext();
        Font f = new Font("Arial", Font.ITALIC, 18);

        TextLayout tl = new TextLayout(t, f, frc);

        g2.setColor(Color.WHITE);
        tl.draw(g2, x, y);

    }

    /**
     * Hilo del crono
     */
    @Override
    public void run()
    {
        try
        {
            while(running)
            {
                time.past();
                Thread.sleep(10);
            }

        }
        catch (InterruptedException e) { System.out.println(e.getMessage()); }
    }

    /**
     * Reinicia el crono
     */
    public void reset()
    {
        time.toZero();
    }

    /**
     * Inicia el crono
     */
    public void go()
    {
        crono.start();
    }
    /**
     * Para el crono
     */
    public void stop()
    {
        running = false;
    }
    public double getTime()
    {
        return time.toSeconds();
    }
    public boolean isRunning()
    {
        return crono.isAlive();
    }

}
